import { createStore, Store, useStore as useVuexStore } from 'vuex'

import login from './login/login'
import system from './main/stytem/stytem'
import dashboard from './main/analysis/dashboard'

import { getPageListData } from '@/service/main/system/ststem'

import { IRootState, IStoreType } from './types'

const store = createStore<IRootState>({
  state: () => {
    return {
      name: 'hy',
      age: 18,
      entireDepartment: [],
      entirerRole: [],
      entirerMenu: []
    }
  },
  mutations: {
    changeEntireDepartment(state, list) {
      state.entireDepartment = list
    },
    changeEntireRole(state, list) {
      state.entirerRole = list
    },
    changeEntirerMenu(state, list) {
      state.entirerMenu = list
    }
  },
  actions: {
    async getInitalDataAction({ commit }) {
      // 1 请求部门和角色数据
      const departementRensult = await getPageListData('/department/list', {
        offset: 0,
        size: 1000
      })
      const { list: departmentList } = departementRensult.data
      const roleResult = await getPageListData('role/list', {
        offset: 0,
        size: 1000
      })
      const { list: roleList } = roleResult.data
      const menuRersult = await getPageListData('/menu/list', {})
      const { list: menuList } = menuRersult.data
      // 2.保存数据
      commit('changeEntireDepartment', departmentList)
      commit('changeEntireRole', roleList)
      commit('changeEntirerMenu', menuList)
    }
  },
  getters: {},
  modules: {
    login,
    system,
    dashboard
  }
})

export function setupStore() {
  store.dispatch('login/loadLocalLogin')
  // store.dispatch('getInitalDataAction')
}

export function useStore(): Store<IStoreType> {
  return useVuexStore()
}

export default store
